using System;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

namespace ToffeeHttp.Runtime.Core
{
    public class HttpRequest
    {
        private          Action<HttpResponse> _onComplete;
        private readonly IMsgChannel          _msgChannel;
        public readonly  UnityWebRequest      webRequest;

        internal HttpRequest(IRequestHandler handler, IMsgChannel channel, Uri uri, object data)
        {
            this._msgChannel     = channel;
            this.webRequest      = handler.RequestCreate(uri, this._msgChannel.Encoder(data));
        }

        public void Send(Action<HttpResponse> onComplete = null)
        {
            this._onComplete = onComplete;
            var request = this.webRequest.SendWebRequest();
            request.completed += this.OnRequestComplete;
        }

        private void OnRequestComplete(AsyncOperation Obj)
        {
            var response = new HttpResponse()
                           {
                               Content    = this._msgChannel.Decoder(this.webRequest),
                               WebRequest = this.webRequest
                           };
            this._onComplete?.Invoke(response);
            this.webRequest.Dispose();
        }
    }
}